import React, { useMemo, useState } from 'react'
import { Layout, Menu } from 'antd'
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
import {
  ContainerOutlined,
  DesktopOutlined,
  MailOutlined,
  HomeOutlined 
} from '@ant-design/icons';
import './App.css'; // 引入外部 CSS 文件

const { Header,  Sider, Content } = Layout;

// 菜单配置
const menuConfig = [
  { key: '1', icon: <HomeOutlined />, label: '首页', path: '/' },
  { key: '2', icon: <DesktopOutlined />, label: '教务管理' },
  {
    key: '3', icon: <ContainerOutlined />, label: '走班排课', 
    children: [
      { key: 'sub1', label: '选课设置', path: '/xk' }
    ]
  },
  { key: '4', icon: <ContainerOutlined />, label: '备课管理' },
  {
    key: 'sub2', label: '作业管理', icon: <MailOutlined />,
    children: [
      { key: '5', label: '作业管理', path: '/homework' },
      { key: '6', label: '作业统计', path: '/status' },

    ]
  },
  { key: '7', icon: <ContainerOutlined />, label: '资料管理', },
  { key: '8', icon: <ContainerOutlined />, label: '配置管理',  },
  { key: '9', icon: <ContainerOutlined />, label: '系统管理', },
];

// 递归构建 key-path 映射和 path-key 映射
function buildKeyPathMaps(items) {
  const keyToPath = {};
  const pathToKey = {};
  function walk(list) {
    list.forEach(item => {
      if (item.path) {
        keyToPath[item.key] = item.path;
        pathToKey[item.path] = item.key;
      }
      if (item.children) walk(item.children);
    });
  }
  walk(items);
  return { keyToPath, pathToKey };
}

// 递归生成 Menu items
function generateMenuItems(config) {
  return config.map(item => {
    const menuItem = {
      key: item.key,
      icon: item.icon,
      label: item.label,
    };
    if (item.children) {
      menuItem.children = generateMenuItems(item.children);
    }
    return menuItem;
  });
}

// 递归查找所有父级key
function findParentKeys(config, targetKey, path = []) {
  for (const item of config) {
    if (item.key === targetKey) {
      return path;
    }
    if (item.children) {
      const found = findParentKeys(item.children, targetKey, [...path, item.key]);
      if (found) return found;
    }
  }
  return null;
}

export default function App() {
  const navigate = useNavigate();
  const location = useLocation();
  const { keyToPath, pathToKey } = useMemo(() => buildKeyPathMaps(menuConfig), []);
  const menuItems = useMemo(() => generateMenuItems(menuConfig), []);

  // 自动高亮
  const selectedKey = useMemo(() => {
    // 精确匹配优先，否则找最长前缀匹配
    let key = pathToKey[location.pathname];
    if (!key) {
      // 找所有前缀，取最长的
      const match = Object.keys(pathToKey)
        .filter(path => location.pathname.startsWith(path))
        .sort((a, b) => b.length - a.length)[0];
      key = pathToKey[match];
    }
    return key ? [key] : [];
  }, [location.pathname, pathToKey]);

  // 自动展开父级菜单（支持多级）
  const openKeys = useMemo(() => {
    if (!selectedKey.length) return [];
    const parentKeys = findParentKeys(menuConfig, selectedKey[0]);
    return parentKeys || [];
  }, [selectedKey]);

  const [openKeysState, setOpenKeysState] = useState(openKeys);

  // 同步路由变化时自动展开父菜单
  React.useEffect(() => {
    setOpenKeysState(openKeys);
  }, [openKeys]);

  // 菜单展开/收起事件
  const handleOpenChange = (keys) => {
    setOpenKeysState(keys);
  };

  // 菜单点击跳转
  const handleMenuClick = ({ key }) => {
    const path = keyToPath[key];
    if (path) navigate(path);
  };

  return (
    <div className="app-container">
      <Layout className="app-layout">
        <Sider width="220" className="app-sider">
          <div className="logo" />
          <Menu
            selectedKeys={selectedKey}
            openKeys={openKeysState}
            mode="inline"
            theme="dark"
            items={menuItems}
            onClick={handleMenuClick}
            onOpenChange={handleOpenChange}
          />
        </Sider>
        <Layout>
          <Header className="app-header">
            学校管理系统
          </Header>
          <Content className="app-content">
            <Outlet />
          </Content>
        </Layout>
      </Layout>
    </div>
  )
}
